package com.spark.trouble

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v4.provider.DocumentFile
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.pavlospt.rxfile.RxFile
import com.spark.colliery.common.ext.gone
import com.spark.common.Api
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.*
import com.spark.common.model.ResultModel
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.common.widget.RejectAlert
import kotlinx.android.synthetic.main.frag_rectify.*

/**
 * 限时整改/挂牌督办
 * 【整改情况】-> 验收说明
 *
 */
class RectifyFragment : BaseFragment() {
    private lateinit var uploadFileAdapter: UploadFileAdapter
    private var taskId = ""
    private val fileIds = mutableListOf<String>()

    companion object {
        val reqFileChooser = 0x9988

        fun newInstance(taskId: String): RectifyFragment {
            val target = RectifyFragment()
            val args = Bundle()
            args.putString("taskId", taskId)
            target.arguments = args
            return target
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_rectify
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        arguments?.apply {
            getString("taskId")?.apply {
                this@RectifyFragment.taskId = this
                fetchRectifyInfo(taskId)
            }
        }
        //方案名称
        tv_scheme
        //方案内容
        et_scheme_desc

        uploadFileAdapter = UploadFileAdapter(R.layout.item_rectify_upload_file).apply {
            setOnItemChildClickListener { adapter, view, position ->
                val file = uploadFileAdapter.data[position]
                when (view.id) {
                    R.id.iv_glance -> {
                        toast("查看文件【${file.fileName}】")
                    }
                    R.id.iv_delete -> {
                        uploadFileAdapter.remove(position)
                        fileIds.removeAt(position)
                    }
                }
            }
            registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
                override fun onChanged() {
                    val dataSize = uploadFileAdapter.data.size
                    ll_file_fake.gone(dataSize == 0)
                    ll_file_real.gone(dataSize != 0)
                }
            })
        }
        recy_upload_files.apply {
            adapter = uploadFileAdapter
            layoutManager = object : LinearLayoutManager(context) {
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
        }
        // 上传文件
        ll_upload_fake.setOnClickListener { invokeFileChooser() }
        ll_upload_real.setOnClickListener { invokeFileChooser() }
        // 暂存
        tv_draft.setOnClickListener {
            activity?.apply {
                RejectAlert.Builder(this, "暂存理由", "请输入暂存理由")
                        .affirm { d, str ->
                            if (str.isNullOrBlank()) {
                                alert("请输入暂存理由")
                            } else {
                                d.dismiss()
                                submitAgencyRehandleVerifyReject(this@RectifyFragment.taskId, str!!)
                            }
                        }
                        .cancel { d, i ->
                            d.dismiss()
                        }
            }
        }
        // 整改完成
        btn_submit.setOnClickListener {
            submitAgencyRehandleVerifyAccept(taskId, et_scheme_desc.string(), fileIds.append(","), "2")
        }
    }

    /**
     * restore state
     */
    private fun restore(
            scheme: String,
            schemeDesc: String,
            files: MutableList<String>
    ) {
        tv_scheme.text = scheme
        et_scheme_desc.setText(schemeDesc)

        val fileIsEmpty = files.isNotEmpty()
        if (fileIsEmpty) {
            val fileModels = mutableListOf<FileModel>()
            files.forEach {
                fileModels.add(FileModel(fileName = it))
            }
            uploadFileAdapter.addData(fileModels)
        }
        ll_file_fake.gone(!fileIsEmpty)
        ll_file_real.gone(fileIsEmpty)
    }

    @SuppressLint("CheckResult")
    private fun fetchRectifyInfo(taskId: String) {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_fetch_limit_supervisor_rectify}", mutableMapOf(Pair("taskId", taskId)).toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            // todo restore
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading()
                        }
                )
    }

    /**
     * invoke the file chooser
     */
    private fun invokeFileChooser() {
        activity?.singleFile(reqFileChooser)
    }

    /**
     * File choose Callback
     */
    fun onFileChooseResult(requestCode: Int, resultCode: Int, intent: Intent?) {
        if (requestCode == reqFileChooser && resultCode == Activity.RESULT_OK) {
            intent?.apply {
                activity?.apply {
                    val docFile = DocumentFile.fromSingleUri(this, intent.data)
                    LogUtils.e("【Choose】[name] ${docFile.name} [type] ${docFile.type} [uri] ${docFile.uri}")
                    RxFile.createFileFromUri(this, docFile.uri)
                            .subscribe {
                                LogUtils.e("[absFile] ${it.absolutePath}")
                                uploadFile(it.absolutePath)
                            }

                }
            }
        }
    }

    /**
     * 上传文件
     */
    @SuppressLint("CheckResult")
    private fun uploadFile(fileUri: String) {
        Api.upload(fileUri)
                .subscribe(
                        {
                            Gson().fromJson(it, FileUploadResultModel::class.java)?.apply {
                                if (code == "200") {
                                    if (resultMaps.isNotEmpty()) {
                                        resultMaps[0].apply {
                                            uploadFileAdapter.addData(FileModel(id = this.fileId.toString(), fileName = this.filename))
                                            fileIds.add(this.fileId.toString())
                                        }
                                    }
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("上传中")
                        }
                )
    }

    /**
     * [待办] -> 待整改
     * todo
     */
    @SuppressLint("CheckResult")
    private fun submitAgencyToRectify(taskId: String) {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_limit_supervisor_to_rectify}", mutableMapOf(Pair("taskId", taskId)).toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            LogUtils.e(it)
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading()
                        }
                )
    }

    /**
     * [待办] 整改验收驳回
     */
    @SuppressLint("CheckResult")
    private fun submitAgencyRehandleVerifyReject(taskId: String, rejectReason: String) {
        val params = mutableMapOf("taskId" to taskId, "refuseReason" to rejectReason)
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_limit_supervisor_submit_rehandle_verify_reject}", params.toJsonBody())
                .subscribe(
                        {
                            Gson().fromJson(it, ResultModel::class.java)?.apply {
                                if (code == "200") {
                                    success("提交成功")
                                    activity?.finish()
                                } else {
                                    error("提交失败")
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中")
                        }
                )
    }

    /**
     * [待办] 整改验收通过
     * @param acceptContent 待办中的整改验收，填写整改验收依据
     * @param acceptFileIdStr 验收文件id
     * @param 结果类型 1 -> 驳回 2 -> 同意
     */
    @SuppressLint("CheckResult")
    private fun submitAgencyRehandleVerifyAccept(taskId: String, acceptContent: String, acceptFileIdStr: String, savesState: String) {
        val params = mutableMapOf("taskId" to taskId,
                "acceptContent" to acceptContent,
                "acceptFileIdStr" to acceptFileIdStr,
                "savesState" to savesState)
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_limit_supervisor_submit_rehandle_verify_accept}", params.toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ResultModel::class.java)?.apply {
                                if (code == "200") {
                                    success("提交成功")
                                    activity?.finish()
                                } else {
                                    error("提交失败")
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中...")
                        }
                )
    }
}

class UploadFileAdapter(layoutRes: Int) : BaseQuickAdapter<FileModel, BaseViewHolder>(layoutRes) {
    override fun convert(helper: BaseViewHolder?, item: FileModel?) {
        if (item == null) return
        helper?.apply {
            val etFileName = getView<EditText>(R.id.tv_file_name).apply {
                setText(item.fileName)
                setOnFocusChangeListener { v, hasFocus ->
                    if (!hasFocus) {
                        if (string().isNullOrBlank()) {
                            mContext.toast("请输入文件名")
                            setText(item.fileName)
                        } else
                            item.fileName = string()
                    } else {
                        setSelection(string().length)
                    }
                }
            }
            getView<ImageView>(R.id.iv_edit).setOnClickListener {
                val inputType = etFileName.inputType
                if (inputType != EditText.AUTOFILL_TYPE_NONE) etFileName.inputType = EditText.AUTOFILL_TYPE_NONE
                else etFileName.inputType = EditText.AUTOFILL_TYPE_TEXT
            }
            getView<ImageView>(R.id.iv_glance).setOnClickListener { onItemChildClickListener?.onItemChildClick(this@UploadFileAdapter, it, adapterPosition) }
            getView<ImageView>(R.id.iv_delete).setOnClickListener { onItemChildClickListener?.onItemChildClick(this@UploadFileAdapter, it, adapterPosition) }
        }
    }
}


data class FileModel(
        var id: String = "",
        var fileName: String = ""
)

data class FileUploadResultModel(
        var msg: String = "", // 上传成功
        var code: String = "", // 200
        var data: Any = Any(), // null
        var resultMaps: List<ResultMap> = listOf()
) {

    data class ResultMap(
            var url: String = "", // http://192.168.1.213:8080/safety/upload/1533069874734.JPG
            var fileId: Int = 0, // 10164
            var filename: String = "",
            var status: Boolean = false // true
    )
}